<template>
<!--    面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

<!--    卡片区-->
    <el-card >
<!--        搜索区-->
        <div style="margin-top: 15px">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input
                            placeholder="请输入内容"
                            v-model="queryInfo.query"
                            clearable
                            @clear = "getUserList()"
                    >
                        <template #append>
                            <el-button icon="el-icon-search"
                                       @click="getUserList()"
                            ></el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                                @click="dialogFormVisible = true"
                    >添加用户</el-button>
                </el-col>
            </el-row>
<!--            用户列表-->
            <el-table
                    :data="userList"
                    border
                    stripe
            >
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template #default="scope">
                        <el-switch
                                v-model="scope.row.mg_state"
                                active-color="#13ce66"
                                inactive-color="gray"
                                @change="userStateChange(scope.row)"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-tooltip content="编辑角色" placement="top">
                            <el-button type="primary" size="mini"
                                       icon="el-icon-edit"
                                       @click="showEditUserDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除角色" placement="top">
                            <el-button type="danger" size="mini"
                                       @click="deleteUser(scope.row.id)"
                                       icon="el-icon-delete"></el-button>
                        </el-tooltip>
                        <el-tooltip content="分配角色" placement="top">
                            <el-button type="warning" size="mini"
                                       @click="showAllotRightDialog(scope.row)"
                                       icon="el-icon-setting"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>

            </el-table>

<!--            添加用户-->
            <el-dialog title="添加用户"
                       v-model="dialogFormVisible"
                       width="50%"
            >
                <el-form :model="AddUserForm"
                         :rules = "AddUserFormRules"
                         ref="AddUserFormRef"
                         label-width="70px"
                >
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="AddUserForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="AddUserForm.password" type="password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="AddUserForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="AddUserForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addDialogClose">取 消</el-button>
                        <el-button type="primary" @click="submitAddUserForm">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
<!--            修改用户-->
            <el-dialog title="修改用户信息"
                       v-model="editUserDialog"
                       width="50%"
            >
                <el-form :model="editUserForm"
                         :rules = "editUserFromRules"
                         ref="editUserFormRef"
                         label-width="70px"
                >
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editUserForm.username"
                                  disabled
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editUserForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editDialogClose">取 消</el-button>
                        <el-button type="primary" @click="submitEditUserForm">确 定</el-button>
                    </span>
                </template>

            </el-dialog>
<!--            分配角色-->
            <el-dialog title="分配角色"
                       v-model="allotRoleDialog"
                       width="40%"
            >
                <el-form ref="form" label-width="120px">
                    <el-form-item label="当前用户:">
                        <el-input v-model="userInfo.username"></el-input>
                    </el-form-item>
                    <el-form-item label="当前角色:">
                        <el-input v-model="userInfo.role_name"></el-input>
                    </el-form-item>
                    <el-form-item label="选择新的角色:">
                        <el-select v-model="selectedRoleId"
                                   placeholder="请选择角色">
                            <el-option v-for="item in roleList"
                                   :key="item.id"
                                   :label="item.roleName"
                                   :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="closeAllotRoleDialog">取 消</el-button>
                        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
                    </span>
                </template>

            </el-dialog>

<!--            分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </el-card>
</template>

<script>
  export default {
    name: "UserList",
    data(){
      //自定义校验规则
      var emailValidator = (rule,value,callback) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if(regEmail.test(value)){
          return callback();
        }else{
          return callback(new Error("请输入正确的邮箱！"))
        }
      }
      var phoneValidator= (rule,value,callback) => {
        const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if(phoneReg.test(value)){
            return callback();
        }else{
          return callback(new Error("请输入正确的手机号"))
        }
      }


      return {
        userList:[],//用户列表
        total:0,
        queryInfo:{
          query:"",//请求参数
          pagenum:1,//请求页码
          pagesize:2,
        },
        dialogFormVisible:false,//添加用户对话框
        AddUserForm:{
          username:"",
          password:"",
          email:"",
          mobile:"",
        },//添加用户的表单
        AddUserFormRules:{
          username:[
            {required:true,message:"请输入用户名",trigger:'blur'},
            {min:3,max:10,message: "用户名3-10字符",trigger: 'blur'},
          ],
          password:[
            {required:true,message:"请输入密码",trigger:'blur'},
            {min:6,max:15,message: "密码6-15字符",trigger: 'blur'},
          ],
          email:[
            {required:true,message:"请输入邮箱号",trigger:'blur'},
            {validator:emailValidator,trigger: 'blur'}
          ],
          mobile:[
            {required:true,message:"请输入手机号",trigger:'blur'},
            {validator:phoneValidator, trigger: 'blur'}
          ]
        },
        //修改用户信息
        editUserDialog:false,
        editId:null,
        editUserForm:{
          username:"",
          email:"",
          mobile:"",
        },
        editUserFromRules:{
          username:[
            {required:true,message:"请输入用户名",trigger:'blur'},
            {min:3,max:10,message: "用户名3-10字符",trigger: 'blur'},
          ],
          email:[
            {required:true,message:"请输入邮箱号",trigger:'blur'},
            {validator:emailValidator,trigger: 'blur'}
          ],
          mobile:[
            {required:true,message:"请输入手机号",trigger:'blur'},
            {validator:phoneValidator, trigger: 'blur'}
          ]
        },
        allotRoleDialog:false,//分配角色dialog
        userInfo:{},//保存用户信息
        roleList:[],//全部角色列表
        selectedRoleId:'',//选中的角色id
      }
    },
    created() {
      this.getUserList();
    },
    methods:{
      //获取用户列表
      async getUserList(){
        const {data:res} = await this.$http.get("/users",{params: this.queryInfo});
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }else{
          this.userList = res.data.users;
          this.total = res.data.total;
        }
      },
      //关闭对话框
      addDialogClose(){
        this.$refs.AddUserFormRef.resetFields();
        this.dialogFormVisible = false;
      },
      //添加新用户
      submitAddUserForm(){
        this.$refs.AddUserFormRef.validate(async valid => {
          if(!valid){
            return this.$message.error("表单信息有误，请核实后重新提交")
          }else{
            const {data:res} = await this.$http.post("/users",this.AddUserForm);
            if(res.meta.status!==201){
              return this.$message({
                type:"error",
                message:res.meta.msg,
              })
            }else{
              this.$message.success(res.meta.msg);
              this.getUserList();
            }
          }
        })
        this.addDialogClose();
      },
      //分页控制
      handleSizeChange(val) {
        this.queryInfo.pagesize =val;
        this.getUserList(this.queryInfo)
      },
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val;
        this.getUserList(this.queryInfo);
      },
      //显示修改用户窗口
      showEditUserDialog(row){
        this.editUserForm.username = row.username;
        this.editUserForm.email = row.email;
        this.editUserForm.mobile = row.mobile;
        this.editId = row.id
        this.editUserDialog = true;
      },
      editDialogClose(){
        this.editUserForm.username = '';
        this.editUserForm.email = '';
        this.editUserForm.mobile = '';
        this.editId = null
        this.editUserDialog = false;
      },
      async submitEditUserForm(){
        const {data:res} = await this.$http.put(`users/${this.editId}`,this.editUserForm);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }else{
          this.$message.success(res.meta.msg);
          this.getUserList();
        }
        this.editDialogClose();
      },
      //状态的切换
      async userStateChange(row){
        const {data:res} = await  this.$http.put(`/users/${row.id}/state/${row.mg_state}`);
        if(res.meta.status !== 200){
          this.$message.error("操作失败！")
          row.mg_state = !row.mg_state
        }else{
          this.$message.success("修改成功")
        }
      },
      //删除用户
      deleteUser(id){
        this.$confirm('确认删除该用户吗？','删除提示',{
          confirmButtonText:"确定",
          cancelButtonText:'取消',
          type:'warning',
        }).then(async () =>{
          const {data:res} = await this.$http.delete(`/users/${id}`)
          console.log(res);
          if(res.meta.status === 200){
            this.$message.success(res.meta.msg);
            this.getUserList();
          }else{
            this.$message.error(res.meta.msg)
          }
        }).catch((err)=>{
          console.log(err);
            this.$message.info("用户取消操作");
        })
      },
      //显示分配角色dialog
      showAllotRightDialog(userInfo){
        this.userInfo = userInfo;
        this.getRoleList();
        this.allotRoleDialog = true;
      },
      //关闭分配
      closeAllotRoleDialog(){
        this.selectedRoleId = null,
        this.allotRoleDialog = false;
      },
      //获取所有角色列表
      async getRoleList(){
        const {data:res} = await  this.$http.get('/roles');
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.roleList = res.data;
      },
      //保存分配的权限
      async saveRoleInfo(){
        if(!this.selectedRoleId){
          return this.$message.warning('请选择新角色！')
        }
        const {data:res} = await this.$http.put(`/users/${this.userInfo.id}/role`,{rid:this.selectedRoleId});
        if(res.meta.status !==200){
          return this.$message.error(re.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.closeAllotRoleDialog();
        this.getUserList();
      }
    }
  }
</script>

<style scoped>
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
    }

</style>
